import User.MessageDTO;
import com.alibaba.fastjson.JSON;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import User.UserDTO;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//import java.io.BufferedReader;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import httpclient.QuickStart;
//import java.io.InputStreamReader;
//import java.math.BigDecimal;
//import java.time.LocalDate;
//import java.util.stream.Collectors;

@WebServlet(urlPatterns = {"/login/dgut"})
public class Servlet_Return extends HttpServlet{

    //关联莞工账号与本地账号
    protected static MessageDTO dgut_login(UserDTO userDTO) {
        boolean flag=false;
        MessageDTO message=null;
        String line=null;
        try{
            BufferedReader bufferedReader=new BufferedReader(new FileReader("src/main/a.txt"));
            while((line=bufferedReader.readLine())!=null) {
                if (line != null) {
                    String[] str = line.split(" ");
                    if (str[0].equals(userDTO.getusername())) {
                        flag = true;
                        message = new MessageDTO(str[0], str[1], str[2], str[3], str[4]);
                        bufferedReader.close();
                        return message;
                    }
                }

            }
            if(!flag){
                message=new MessageDTO(userDTO.getusername(),null,"123456",null,"img1.jpg");
                return message;

            }
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
        } catch (IOException e) {
            System.out.println("用户登录失败，请先注册！");
        }
        return message;
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException
    {

        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//向http://cas.gemcho.com/ssoapi/v2/checkToken发送post请求获取用户信息
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        String token=req.getParameter("token");
        String appid="javaee";
        String appsecret = "b3b52e43ccfd";
        String userip = req.getRemoteAddr();     //获取本地ip
        String url = "https://cas.dgut.edu.cn/ssoapi/v2/checkToken";
        List<NameValuePair> s = new ArrayList<>();
        s.add(new BasicNameValuePair("token",token));
        s.add(new BasicNameValuePair("appid",appid));
        s.add(new BasicNameValuePair("appsecret",appsecret));
        s.add(new BasicNameValuePair("userip",userip));
        String json = QuickStart.post(url,s);


        OpenidDTO oid= JSON.parseObject(json,OpenidDTO.class);
        //System.out.println(oid);
        if(oid.getError()!=null){
            String access_token = oid.getAccess_token();
            String openid = oid.getOpenid();
            List<NameValuePair> s1 = new ArrayList<>();
            s1.add(new BasicNameValuePair("access_token",access_token));
            s1.add(new BasicNameValuePair("openid",openid));
            String json1=QuickStart.post("https://cas.dgut.edu.cn/oauth/getUserInfo",s1);
            Jsonb jsonb= JsonbBuilder.create();
            UserDTO user=jsonb.fromJson(json1,UserDTO.class);
            // UserDTO user=JSON.parseObject(json1, UserDTO.class);

            if(user.getError()!=null){
                UserDTO userDTO=new UserDTO("1","","","","","");
                Jsonb jsonb1 = JsonbBuilder.create();
                String jsonPerson = jsonb1.toJson(userDTO);
                resp.getWriter().write(jsonPerson);
            }
            else{
                MessageDTO message=null;
                message=dgut_login(user);
                if(message!=null)
                {
                    if(message.getname().equals(user.getusername()))
                    {
                        String line =message.getname()+" "+message.gete_mail()+" "+message.getpassword()+" "+message.getPhone()+" "+message.getimg();
                        try{
                            BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter("src/main/a.txt",true));
                            bufferedWriter.write(line);
                            bufferedWriter.newLine();
                            bufferedWriter.close();
                        } catch (IOException e) {
                            resp.sendRedirect("error.jsp");
                        }
                        req.getSession().setAttribute("LocalUser",message);
                        resp.sendRedirect("http://localhost:8080/userinfo.jsp");
                    }
                    else resp.sendRedirect("error.jsp");
                }
                else resp.sendRedirect("error.jsp");
            }
        }
        else{
            OpenidDTO myDTO=new OpenidDTO("1","token不存在或已过期","","");
            Jsonb jsonb = JsonbBuilder.create();
            String jsonPerson = jsonb.toJson(myDTO);
            resp.getWriter().write(jsonPerson);

        }

    }

}
